#!/usr/bin/env bash

set -euo pipefail

ROOT_DIR=$(cd -- "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
PID_FILE="$ROOT_DIR/.agent-society-stack.pids"
LOG_DIR="$ROOT_DIR/logs"
BACKEND_PORT=${BACKEND_PORT:-8080}
DEFAULT_API_BASE="http://localhost:${BACKEND_PORT}"

start_services() {
  if [[ -f "$PID_FILE" ]]; then
    if pgrep -F "$PID_FILE" >/dev/null 2>&1; then
      echo "Stack appears to be running (PID file $PID_FILE). Use --stop first." >&2
      exit 1
    fi
    rm -f "$PID_FILE"
  fi

  local uvicorn_bin="$ROOT_DIR/venv/bin/uvicorn"
  if [[ ! -x "$uvicorn_bin" ]]; then
    echo "uvicorn not found at $uvicorn_bin. Ensure the virtualenv is installed." >&2
    exit 1
  fi

  if ! command -v npm >/dev/null 2>&1; then
    echo "npm is required to run the frontend (not found on PATH)." >&2
    exit 1
  fi

  mkdir -p "$LOG_DIR"

  echo "Starting backend on port $BACKEND_PORT…"
  (
    cd "$ROOT_DIR"
    nohup "$uvicorn_bin" agent_society.ledger.service:app --host 0.0.0.0 --port "$BACKEND_PORT" \
      > "$LOG_DIR/backend.log" 2>&1 &
    echo $! > "$PID_FILE"
  )

  echo "Starting frontend dev server…"
  (
    cd "$ROOT_DIR"
    NEXT_PUBLIC_API_BASE="${NEXT_PUBLIC_API_BASE:-$DEFAULT_API_BASE}" \
      nohup npm run --workspace ide dev > "$LOG_DIR/frontend.log" 2>&1 &
    echo $! >> "$PID_FILE"
  )

  echo "Backend log:   $LOG_DIR/backend.log"
  echo "Frontend log:  $LOG_DIR/frontend.log"
  echo "PID file:      $PID_FILE"
}

stop_services() {
  if [[ ! -f "$PID_FILE" ]]; then
    echo "No PID file found ($PID_FILE). Nothing to stop." >&2
    return 0
  fi

  local pids
  mapfile -t pids < "$PID_FILE"
  local stopped_any=false
  for pid in "${pids[@]}"; do
    if [[ -n "$pid" ]] && kill -0 "$pid" >/dev/null 2>&1; then
      echo "Stopping process $pid…"
      kill "$pid" >/dev/null 2>&1 || true
      stopped_any=true
    fi
  done

  if [[ "$stopped_any" == true ]]; then
    # wait a moment and force kill if required
    sleep 1
    for pid in "${pids[@]}"; do
      if [[ -n "$pid" ]] && kill -0 "$pid" >/dev/null 2>&1; then
        echo "Force killing lingering process $pid…"
        kill -9 "$pid" >/dev/null 2>&1 || true
      fi
    done
  fi

  rm -f "$PID_FILE"
  echo "Stack stopped."
}

case "${1:-}" in
  --stop)
    stop_services
    ;;
  "")
    start_services
    ;;
  *)
    echo "Usage: $0 [--stop]" >&2
    exit 1
    ;;
esac
